package com.atzongmaotan.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * ClassName:    GlobalExceptionHandler
 * Package:  com.atzongmaotan.common
 * Description:
 *      全局异常处理
 * @Author: interface
 * @Create: 2024/6/12 - 上午7:33
 * @Version: v1.0
 */
@Slf4j
@ControllerAdvice(annotations = {Controller.class, RestController.class})
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] splits = e.getMessage().split(" ");
            String msg = splits[2]+" 已存在 ";
            return R.error(msg);
        }
        return R.error("未知错误");
    }
    @ExceptionHandler(value = CustomeException.class)
    public R<String> exceptionHandler(CustomeException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }
}
